import os
import matplotlib.pyplot as plt

def process_time_differences(file_path):
    """
    读取文本文件，提取时间戳，计算相邻时间戳的时间差，并返回最大值、最小值和平均间隔。
    :param file_path: txt 文件路径
    :return: 最大时间差、最小时间差、平均间隔
    """
    if not os.path.exists(file_path):
        print("文件不存在！")
        return

    time_stamps = []

    # 读取文件中的时间戳
    with open(file_path, 'r') as file:
        for line in file:
            line = line.strip()
            if line:  # 确保非空行
                parts = line.split()  # 按空格分割
                try:
                    # 提取第一列作为时间戳
                    time_stamps.append(float(parts[0]))
                except (ValueError, IndexError):
                    print(f"无效的行：{line}")
                    continue

    # 检查是否有足够的时间戳
    if len(time_stamps) < 2:
        print("时间戳不足以计算差值！")
        return

    # 计算时间差
    time_differences = [
        time_stamps[i + 1] - time_stamps[i] for i in range(len(time_stamps) - 1)
    ]

    # 计算最大值、最小值和平均间隔
    max_diff = max(time_differences)
    min_diff = min(time_differences)
    avg_diff = sum(time_differences) / len(time_differences)

    print(f'path: {os.path.basename(file_path)}')
    print(f"最大时间差: {max_diff} ms")
    print(f"最小时间差: {min_diff} ms")
    print(f"平均时间间隔: {avg_diff} ms")

    # 可视化时间间隔分布
    visualize_time_differences(time_differences, max_diff, min_diff)

    return max_diff, min_diff, avg_diff


def visualize_time_differences(time_differences, max_diff, min_diff):
    """
    可视化时间间隔的分布。
    :param time_differences: 时间间隔列表
    :param max_diff: 最大时间间隔
    :param min_diff: 最小时间间隔
    """
    # 绘制柱状图
    plt.figure(figsize=(10, 6))
    plt.hist(time_differences, bins=20, color='skyblue', edgecolor='black', alpha=0.7)

    # 添加标题和标签
    plt.title("distrubition", fontsize=16)
    plt.xlabel("time_gap (ms)", fontsize=14)
    plt.ylabel("cnt", fontsize=14)

    # 显示最大值和最小值的标注
    plt.axvline(max_diff, color='red', linestyle='--', label=f'max: {max_diff:.2f} ms')
    plt.axvline(min_diff, color='green', linestyle='--', label=f'min: {min_diff:.2f} ms')
    plt.legend(fontsize=12)

    # 显示图表
    plt.tight_layout()
    plt.show()


# 示例用法
if __name__ == "__main__":
    file_path = "time_stamps.txt"  # 替换为你的文件路径
    process_time_differences(file_path)



# 示例用法
if __name__ == "__main__":
    # file_path = "/home/ai/dataset/0331/20250331070337"  # 替换为你的文件路径
    file_path = "/home/ai/dataset/0331/20250331071655"  # 替换为你的文件路径

    depth_path = os.path.join(file_path, 'depth.txt')
    left_path = os.path.join(file_path, 'left_ir.txt')
    right_path = os.path.join(file_path, 'right_ir.txt')

    # process_time_differences(depth_path)
    # process_time_differences(left_path)
    process_time_differences(right_path)
